package bch.rocketmq.test;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;

public class VarHandleExample {
    private volatile int x = 0;

    private static VarHandle X_HANDLE;

    static {
        try {
            X_HANDLE = MethodHandles.lookup()
                    .in(VarHandleExample.class)
                    .findVarHandle(VarHandleExample.class, "x", int.class);
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    public static void main(String[] args) {
        VarHandleExample example = new VarHandleExample();

        // 普通读写
        X_HANDLE.set(example, 10);
        System.out.println("x=" + X_HANDLE.get(example));

        // CAS 原子更新
        boolean success = X_HANDLE.compareAndSet(example, 10, 20);
        System.out.println("CAS success? " + success + ", x=" + example.x);

        // 原子自增
        int old = (int) X_HANDLE.getAndAdd(example, 5);
        System.out.println("old=" + old + ", new=" + example.x);
    }
}
